package cn.spring.cloud.activity.mybatisps.springbootrabbitmq.utils;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

/**
 * @ClassName: SmsUtil
 * @Author: 清风一阵吹我心
 * @Description: TODO 阿里云发送短信验证码的工具类
 * @Date: 2019/10/26 13:37
 * @Version 1.0
 **/
@Component
public class smsUtil {

    private static final String regionId = "cn-hangzhou";

    /**
     * 产品域名
     */
    private static final String DOMAIN = "dysmsapi.aliyuncs.com";
    /**
     * 系统规定参数。取值：SendSms
     */
    private static final String ACTION = "SendSms";

    /**
     * 可以得到当前配置文件中所有的信息
     */
    @Autowired
    private Environment environment;

    /**
     * //TODO
     * 发送短信
     *
     * @param phoneNumbers  手机号
     * @param signName      短信签名名称
     * @param templateCode  短信模板ID
     * @param templateParam 参数
     * @return com.aliyuncs.CommonResponse
     */
    public CommonResponse sendSms(String phoneNumbers, String signName, String templateCode, String templateParam) {
        String accessKeyId = environment.getProperty("aliyun.sms.accessKeyId");
        String accessKeySecret = environment.getProperty("aliyun.sms.accessKeySecret");
        //调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "5000");
        System.setProperty("sun.net.client.defaultReadTimeout", "5000");

        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain(DOMAIN);
        request.setVersion("2017-05-25");
        request.setAction(ACTION);
        //待发送手机号
        request.putQueryParameter("PhoneNumbers", phoneNumbers);
        //短信签名
        request.putQueryParameter("SignName", signName);
        //短信模板Id
        request.putQueryParameter("TemplateCode", templateCode);
        //短信模板变量对应的实际值，JSON格式。如果JSON中需要带换行符，请参照标准的JSON协议处理。
        request.putQueryParameter("TemplateParam", templateParam);
        //上行短信扩展码，无特殊需要此字段的用户请忽略此字段。
        //request.putQueryParameter("SmsUpExtendCode", "0000");
        //外部流水扩展字段
        //request.putQueryParameter("OutId", "0000");

        CommonResponse commonResponse = null;
        try {
            commonResponse = client.getCommonResponse(request);
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return commonResponse;
    }
}
